package org.example.data_stream;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.List;

/**
 * 归约测试
 * @author shenguangyang
 */
public class E08_TransformReduce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        List<Event> events = new ArrayList<Event>() {{
            add(new Event("user01", "./home1", 1000L));
            add(new Event("user02", "./cart", 2000L));
            add(new Event("user02", "./prod?id=10`", 3800L));
            add(new Event("user02", "./prod?id=2`", 3000L));
            add(new Event("user01", "./prod?id=15`", 4000L));
        }};
        DataStream<Event> streamSource = env.fromCollection(events);

        // 1. 统计每个用户的访问频次
        SingleOutputStreamOperator<Tuple2<String, Long>> clickByUser =
                streamSource
                        .map((MapFunction<Event, Tuple2<String, Long>>) event -> Tuple2.of(event.getUser(), 1L))
                        .returns(new TypeHint<Tuple2<String, Long>>() {})
                        .keyBy((KeySelector<Tuple2<String, Long>, Object>) data -> data.f0)
                        .reduce((ReduceFunction<Tuple2<String, Long>>) (value1, value2) -> Tuple2.of(value1.f0, value1.f1 + value2.f1));

        // 2. 选取当前最活跃的用户
        SingleOutputStreamOperator<Tuple2<String, Long>> reduce = clickByUser
                .keyBy(data -> "key")
                .reduce((ReduceFunction<Tuple2<String, Long>>) (v1, v2) -> v1.f1 > v2.f1 ? v1 : v2);

        reduce.print("active user: ");

        env.execute();
    }
}
